

package com.sixfoot.adminsys.frames.user;

import com.sixfoot.adminsys.Chooser;
import com.sixfoot.adminsys.DemoProperties;
import com.sixfoot.adminsys.frames.Stacker;
import com.sixfoot.adminsys.utilities.UIUtils;
import com.sixfoot.dao.UserRepository;
import com.sixfoot.domain.User;
import com.sixfoot.facade.user.UserDto;
import com.sixfoot.service.RoleService;
import com.sixfoot.service.UserService;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.sixfoot.adminsys.frames.user.UserTableModel.*;
import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;


@DemoProperties(value = "用户列表",
		category = "用户管理",
		description = ""
    )
public class UserTable extends JPanel {
	private UserRepository userRepository = (UserRepository) UIUtils.getBean("userRepository");
	private UserService userService = (UserService) UIUtils.getBean("userService");
	private JPanel controlPanel;
	private Stacker dataPanel;
	private JTable userTable;
	private JTextField filterField;
	private JLabel tableStatus;

	private Color[] rowColors;
	private String searchLabelString;

	private String filterString = null;

	private TableRowSorter sorter;
	private RowFilter<UserTableModel, Integer> searchFilter;
	private UserTableModel userTableModel;

	public UserTable() {
		initModel();
		initComponents();
		initSortingFiltering();
	}

	protected void initModel() {
		userTableModel = new UserTableModel();

	}

	protected void initComponents() {
		setLayout(new BorderLayout());

		controlPanel = createControlPanel();
		add(controlPanel, BorderLayout.NORTH);

		// <snip>Create JTable
		userTable = new JTable(userTableModel);
		// </snip>

		// </snip>Set JTable display properties
		userTable.setColumnModel(createColumnModel());
		userTable.setAutoCreateRowSorter(true);
		userTable.setRowHeight(26);
		userTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		userTable.setIntercellSpacing(new Dimension(0, 0));
		// </snip>

		// <snip>Initialize preferred size for table's viewable area
		Dimension viewSize = new Dimension();
		viewSize.width = userTable.getColumnModel().getTotalColumnWidth();
		viewSize.height = 10 * userTable.getRowHeight();
		userTable.setPreferredScrollableViewportSize(viewSize);
		// </snip>

		// <snip>Customize height and alignment of table header
		JTableHeader header = userTable.getTableHeader();
		header.setPreferredSize(new Dimension(30, 26));
		TableCellRenderer headerRenderer = header.getDefaultRenderer();
		if (headerRenderer instanceof JLabel) {
			((JLabel) headerRenderer).setHorizontalAlignment(JLabel.CENTER);
		}
		// </snip>

		JScrollPane scrollpane = new JScrollPane(userTable);
		dataPanel = new Stacker(scrollpane);
		add(dataPanel, BorderLayout.CENTER);

		add(createStatusBar(), BorderLayout.SOUTH);

	}

	protected JPanel createControlPanel() {
		JPanel controlPanel = new JPanel();
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		controlPanel.setLayout(gridbag);

		c.gridx = 0;
		c.gridy = 1;
		c.gridheight = 1;
		c.insets = new Insets(20, 10, 0, 10);
		c.anchor = GridBagConstraints.SOUTHWEST;
		JLabel searchLabel = new JLabel("输入姓名进行搜索");
		controlPanel.add(searchLabel, c);

		c.gridx = 0;
		c.gridy = 2;
		c.weightx = 1.0;
		c.insets.top = 0;
		c.insets.bottom = 12;
		c.anchor = GridBagConstraints.SOUTHWEST;
		// c.fill = GridBagConstraints.HORIZONTAL;
		filterField = new JTextField(24);
		filterField.getDocument().addDocumentListener(
				new SearchFilterListener());
		controlPanel.add(filterField, c);

		c.gridx = 1;
		c.gridy = 2;
		c.gridwidth = GridBagConstraints.REMAINDER;
		c.weightx = 0.0;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.NONE;
		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS));
        JButton addUserBtn = new JButton("添加用户");
        addUserBtn.addActionListener(new AddUserListener());
        btnPanel.add(addUserBtn);

        btnPanel.add(Box.createRigidArea(new Dimension(10, 10)));
        JButton editUserBtn = new JButton("编辑用户");
        editUserBtn.addActionListener(new EditUserListener());
        btnPanel.add(editUserBtn);
		controlPanel.add(btnPanel, c);
        return controlPanel;
	}

	protected class SearchFilterListener implements DocumentListener {
		protected void changeFilter(DocumentEvent event) {
			Document document = event.getDocument();
			try {
				setFilterString(document.getText(0, document.getLength()));

			} catch (Exception ex) {
				ex.printStackTrace();
				System.err.println(ex);
			}
		}

		public void changedUpdate(DocumentEvent e) {
			changeFilter(e);
		}

		public void insertUpdate(DocumentEvent e) {
			changeFilter(e);
		}

		public void removeUpdate(DocumentEvent e) {
			changeFilter(e);
		}
	}

	protected Container createStatusBar() {
		searchLabelString = "记录数 ";

		Box statusBar = Box.createHorizontalBox();


		// Middle (should stretch)
		statusBar.add(Box.createHorizontalGlue());
		statusBar.add(Box.createHorizontalGlue());
		statusBar.add(Box.createVerticalGlue());

		// Right status area
		tableStatus = new JLabel(searchLabelString +"0");
		statusBar.add(tableStatus);
		statusBar.add(Box.createHorizontalStrut(12));
	 	userTableModel.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				// Get rowCount from *table*, not model, as the view row count
				// may be different from the model row count due to filtering
				tableStatus.setText(searchLabelString + userTable.getRowCount());
			}
		});

		return statusBar;
	}

	private Color[] getTableRowColors() {
		if (rowColors == null) {
			rowColors = new Color[2];
			rowColors[0] = UIManager.getColor("Table.background");
			rowColors[1] = new Color((int) (rowColors[0].getRed() * .9),
					(int) (rowColors[0].getGreen() * .9),
					(int) (rowColors[0].getBlue() * .9));
		}
		return rowColors;
	}


	public void start() {
		loadData();
	}

	// <snip>Initialize table columns
	protected TableColumnModel createColumnModel() {
		DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
		TableCellRenderer cellRenderer = new UserCellRenderers.RowRenderer(
				getTableRowColors());

		TableColumn column = new TableColumn();
		column.setModelIndex(realName_column);
		column.setHeaderValue("姓名");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(sex_column);
		column.setHeaderValue("性别");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(birthday_column);
		column.setHeaderValue("生日");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(mobile_column);
		column.setHeaderValue("手机");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(height_column);
		column.setHeaderValue("身高");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(weight_column);
		column.setHeaderValue("体重");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(workingPlace_column);
		column.setHeaderValue("工作单位");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(position_column);
		column.setHeaderValue("职位");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(medicalHistory_column);
		column.setHeaderValue("病史");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(locked_column);
		column.setHeaderValue("是否锁定");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(roles_column);
		column.setHeaderValue("角色");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		return columnModel;
	}

	// </snip>

	// <snip>Use SwingWorker to asynchronously load the data

	public void loadData() {
		List<User> users = new ArrayList<>();
		Iterable<User> iterable = userRepository.findAll();
		Iterator<User> iterator = iterable.iterator();
		while (iterator.hasNext()) {
			users.add(iterator.next());
		}
		userTableModel.add(users);
	}

	public void setFilterString(String filterString) {
		String oldFilterString = this.filterString;
		this.filterString = filterString;
		if (filterString != null && !filterString.equals("")) {
			sorter.setRowFilter(searchFilter);
		} else {
			sorter.setRowFilter(null);
		}
		tableStatus.setText(searchLabelString + userTable.getRowCount());
		firePropertyChange("filterString", oldFilterString, filterString);
	}

	protected void initSortingFiltering() {
		// <snip>Setup filtering for winners
		sorter = new TableRowSorter(userTableModel);
		userTable.setRowSorter(sorter);
		// </snip>

		// <snip>Setup search filter
		searchFilter = new RowFilter<UserTableModel, Integer>() {
			public boolean include(
					Entry<? extends UserTableModel, ? extends Integer> entry) {
				UserTableModel userTableModel = entry.getModel();
				User user = userTableModel.getUser(entry
						.getIdentifier().intValue());
				boolean matches = false;

				String realName = user.getRealName();
				if (realName != null) {
					// Returning true indicates this row should be shown.
					matches = realName.contains(filterString);
				}
				return matches;
			}
		};
		// </snip>
	}

    // 监听添加用户按钮点击
    private class AddUserListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            Object[] message = new Object[25];
            JLabel nameLabel = new JLabel("姓名（必填）");
            JLabel sexLabel = new JLabel("性别（必填）");
            JLabel birthdayLabel = new JLabel("生日");
            JLabel mobileLabel = new JLabel("手机");
            JLabel heightLabel = new JLabel("身高（cm）");
            JLabel weightLabel = new JLabel("体重（kg）");
            JLabel workingPlaceLabel = new JLabel("工作单位");
            JLabel positionLabel = new JLabel("职位");
            JLabel medicalHistoryLabel = new JLabel("病史");
            JLabel lockedLabel = new JLabel("是否锁定");
            JTextField name = new JTextField();
            ButtonGroup sex_group = new ButtonGroup();
            JRadioButton sex_boy = new JRadioButton("男");
            JRadioButton sex_girl = new JRadioButton("女");
            sex_group.add(sex_boy);
            sex_group.add(sex_girl);
            JTextField birthday = new JTextField();
            Chooser ser = Chooser.getInstance();
            ser.register(birthday);
            JTextField mobile = new JTextField();
            JTextField height = new JTextField();
            JTextField weight = new JTextField();
            JTextField workingPlace = new JTextField();
            JTextField position = new JTextField();
            JTextField medicalHistory = new JTextField();
            ButtonGroup lock_group = new ButtonGroup();
            JRadioButton noLock = new JRadioButton("未锁定");
            noLock.setSelected(true);
            JRadioButton isLock = new JRadioButton("锁定");
            lock_group.add(isLock);
            lock_group.add(noLock);

            height.addKeyListener(new KeyAdapter(){
                public void keyTyped(KeyEvent e) {
                    int keyChar = e.getKeyChar();
                    if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){

                    }else{
                        e.consume(); //关键，屏蔽掉非法输入
                    }
                }
            });

            weight.addKeyListener(new KeyAdapter(){
                public void keyTyped(KeyEvent e) {
                    int keyChar = e.getKeyChar();
                    if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){

                    }else{
                        e.consume(); //关键，屏蔽掉非法输入
                    }
                }
            });

            JPanel p1 = new JPanel();
            p1.setLayout(new BoxLayout(p1 ,BoxLayout.X_AXIS));
            p1.add(nameLabel);
            p1.add(Box.createRigidArea(new Dimension(10, 10)));
            p1.add(name);

            JPanel p2 = new JPanel();
            p2.setLayout(new BoxLayout(p2 ,BoxLayout.X_AXIS));
            p2.add(sexLabel);
            p2.add(Box.createRigidArea(new Dimension(10, 10)));
            p2.add(sex_boy);
            p2.add(Box.createRigidArea(new Dimension(20, 10)));
            p2.add(sex_girl);

            JPanel p3 = new JPanel();
            p3.setLayout(new BoxLayout(p3 ,BoxLayout.X_AXIS));
            p3.add(birthdayLabel);
            p3.add(Box.createRigidArea(new Dimension(60, 10)));
            p3.add(birthday);


            JPanel p4 = new JPanel();
            p4.setLayout(new BoxLayout(p4 ,BoxLayout.X_AXIS));
            p4.add(mobileLabel);
            p4.add(Box.createRigidArea(new Dimension(60, 10)));
            p4.add(mobile);

            JPanel p5 = new JPanel();
            p5.setLayout(new BoxLayout(p5 ,BoxLayout.X_AXIS));
            p5.add(heightLabel);
            p5.add(Box.createRigidArea(new Dimension(16, 10)));
            p5.add(height);

            JPanel p6 = new JPanel();
            p6.setLayout(new BoxLayout(p6 ,BoxLayout.X_AXIS));
            p6.add(weightLabel);
            p6.add(Box.createRigidArea(new Dimension(20, 10)));
            p6.add(weight);

            JPanel p7 = new JPanel();
            p7.setLayout(new BoxLayout(p7 ,BoxLayout.X_AXIS));
            p7.add(workingPlaceLabel);
            p7.add(Box.createRigidArea(new Dimension(34, 10)));
            p7.add(workingPlace);

            JPanel p8 = new JPanel();
            p8.setLayout(new BoxLayout(p8 ,BoxLayout.X_AXIS));
            p8.add(positionLabel);
            p8.add(Box.createRigidArea(new Dimension(60, 10)));
            p8.add(position);

            JPanel p9 = new JPanel();
            p9.setLayout(new BoxLayout(p9 ,BoxLayout.X_AXIS));
            p9.add(medicalHistoryLabel);
            p9.add(Box.createRigidArea(new Dimension(60, 10)));
            p9.add(medicalHistory);

            JPanel p10 = new JPanel();
            p10.setLayout(new BoxLayout(p10 ,BoxLayout.X_AXIS));
            p10.add(lockedLabel);
            p10.add(Box.createRigidArea(new Dimension(34, 10)));
            p10.add(isLock);
            p10.add(Box.createRigidArea(new Dimension(15, 10)));
            p10.add(noLock);

            message[0] = p1;
            message[1] = p2;
            message[2] = p3;
            message[3] = p4;
            message[4] = p5;
            message[5] = p6;
            message[6] = p7;
            message[7] = p8;
            message[8] = p9;
            message[9] = p10;
            String[] options = {"确定"};
            int result = JOptionPane.showOptionDialog(
                    UserTable.this,                        // the parent that the dialog blocks
                    message,                                    // the dialog message array
                    "添加角色", // the title of the dialog window
                    JOptionPane.DEFAULT_OPTION,                 // option type
                    JOptionPane.PLAIN_MESSAGE,            // message type
                    null,                                       // optional icon, use null to use the default icon
                    options,                                    // options string array, will be made into buttons
                    options[0]                                  // option that should be made into a default button
            );
            if (result == 0) {
                if (name.getText() == null || name.getText().trim().length() == 0) {
                    UIUtils.showWarning("请填写姓名！");
                    return;
                }
                if (sex_boy.isSelected() == false && sex_girl.isSelected() == false) {
                    UIUtils.showWarning("请填写性别！");
                    return;
                }
                User user = new User();
                user.setRealName(name.getText());
                user.setUsername(name.getText());
                user.setPassword("123456");
                if (sex_boy.isSelected()) {
                    user.setSex(1);
                } else {
                    user.setSex(0);
                }
                if (birthday.getText() != null && !"".equals(birthday.getText())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        java.util.Date birthDate = sdf.parse(birthday.getText());
                        user.setBirthday(birthDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                user.setMobile(mobile.getText());
                user.setHeight(!"".equals(height.getText()) ? Integer.parseInt(height.getText()) : null);
                user.setWeight(!"".equals(weight.getText()) ? Integer.parseInt(weight.getText()) : null);
                user.setWorkingPlace(workingPlace.getText());
                user.setPosition(position.getText());
                user.setMedicalHistory(medicalHistory.getText());
                if (noLock.isSelected()) {
                    user.setLocked(false);
                } else {
                    user.setLocked(true);
                }
                User userDB = userRepository.save(user);
                userTableModel.add(userDB);
                UIUtils.showInfo("添加用户成功！");
            }


        }
    }

    // 监听添加用户按钮点击
    private class EditUserListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            int selectedRow = userTable.getSelectedRow();
            if (selectedRow == -1) {
                UIUtils.showWarning("请选择要编辑的用户！");
                return;
            }
            User editUser = userTableModel.getUser(selectedRow);
            Object[] message = new Object[25];
            JLabel nameLabel = new JLabel("姓名（必填）");
            JLabel sexLabel = new JLabel("性别（必填）");
            JLabel birthdayLabel = new JLabel("生日");
            JLabel mobileLabel = new JLabel("手机");
            JLabel heightLabel = new JLabel("身高（cm）");
            JLabel weightLabel = new JLabel("体重（kg）");
            JLabel workingPlaceLabel = new JLabel("工作单位");
            JLabel positionLabel = new JLabel("职位");
            JLabel medicalHistoryLabel = new JLabel("病史");
            JLabel lockedLabel = new JLabel("是否锁定");
            JTextField name = new JTextField();
            name.setText(editUser.getRealName());
            ButtonGroup sex_group = new ButtonGroup();
            JRadioButton sex_boy = new JRadioButton("男");
            JRadioButton sex_girl = new JRadioButton("女");
            if (editUser.getSex() == 1) {
                sex_boy.setSelected(true);
            } else {
                sex_girl.setSelected(true);
            }
            sex_group.add(sex_boy);
            sex_group.add(sex_girl);
            JTextField birthday = new JTextField();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(editUser.getBirthday());
            birthday.setText(format);
            Chooser ser = Chooser.getInstance();
            ser.register(birthday);
            JTextField mobile = new JTextField();
            mobile.setText(editUser.getMobile());
            JTextField height = new JTextField();
            height.setText(editUser.getHeight() != null ? editUser.getHeight().toString() : "");
            JTextField weight = new JTextField();
            weight.setText(editUser.getWeight() != null ? editUser.getWeight().toString() : "");
            JTextField workingPlace = new JTextField();
            workingPlace.setText(editUser.getWorkingPlace());
            JTextField position = new JTextField();
            position.setText(editUser.getPosition());
            JTextField medicalHistory = new JTextField();
            medicalHistory.setText(editUser.getMedicalHistory());
            ButtonGroup lock_group = new ButtonGroup();
            JRadioButton noLock = new JRadioButton("未锁定");
            JRadioButton isLock = new JRadioButton("锁定");
            if (editUser.getLocked()) {
                isLock.setSelected(true);
            } else {
                noLock.setSelected(true);
            }
            lock_group.add(isLock);
            lock_group.add(noLock);

            height.addKeyListener(new KeyAdapter(){
                public void keyTyped(KeyEvent e) {
                    int keyChar = e.getKeyChar();
                    if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){

                    }else{
                        e.consume(); //关键，屏蔽掉非法输入
                    }
                }
            });

            weight.addKeyListener(new KeyAdapter(){
                public void keyTyped(KeyEvent e) {
                    int keyChar = e.getKeyChar();
                    if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){

                    }else{
                        e.consume(); //关键，屏蔽掉非法输入
                    }
                }
            });

            JPanel p1 = new JPanel();
            p1.setLayout(new BoxLayout(p1 ,BoxLayout.X_AXIS));
            p1.add(nameLabel);
            p1.add(Box.createRigidArea(new Dimension(10, 10)));
            p1.add(name);

            JPanel p2 = new JPanel();
            p2.setLayout(new BoxLayout(p2 ,BoxLayout.X_AXIS));
            p2.add(sexLabel);
            p2.add(Box.createRigidArea(new Dimension(10, 10)));
            p2.add(sex_boy);
            p2.add(Box.createRigidArea(new Dimension(20, 10)));
            p2.add(sex_girl);

            JPanel p3 = new JPanel();
            p3.setLayout(new BoxLayout(p3 ,BoxLayout.X_AXIS));
            p3.add(birthdayLabel);
            p3.add(Box.createRigidArea(new Dimension(60, 10)));
            p3.add(birthday);


            JPanel p4 = new JPanel();
            p4.setLayout(new BoxLayout(p4 ,BoxLayout.X_AXIS));
            p4.add(mobileLabel);
            p4.add(Box.createRigidArea(new Dimension(60, 10)));
            p4.add(mobile);

            JPanel p5 = new JPanel();
            p5.setLayout(new BoxLayout(p5 ,BoxLayout.X_AXIS));
            p5.add(heightLabel);
            p5.add(Box.createRigidArea(new Dimension(16, 10)));
            p5.add(height);

            JPanel p6 = new JPanel();
            p6.setLayout(new BoxLayout(p6 ,BoxLayout.X_AXIS));
            p6.add(weightLabel);
            p6.add(Box.createRigidArea(new Dimension(20, 10)));
            p6.add(weight);

            JPanel p7 = new JPanel();
            p7.setLayout(new BoxLayout(p7 ,BoxLayout.X_AXIS));
            p7.add(workingPlaceLabel);
            p7.add(Box.createRigidArea(new Dimension(34, 10)));
            p7.add(workingPlace);

            JPanel p8 = new JPanel();
            p8.setLayout(new BoxLayout(p8 ,BoxLayout.X_AXIS));
            p8.add(positionLabel);
            p8.add(Box.createRigidArea(new Dimension(60, 10)));
            p8.add(position);

            JPanel p9 = new JPanel();
            p9.setLayout(new BoxLayout(p9 ,BoxLayout.X_AXIS));
            p9.add(medicalHistoryLabel);
            p9.add(Box.createRigidArea(new Dimension(60, 10)));
            p9.add(medicalHistory);

            JPanel p10 = new JPanel();
            p10.setLayout(new BoxLayout(p10 ,BoxLayout.X_AXIS));
            p10.add(lockedLabel);
            p10.add(Box.createRigidArea(new Dimension(34, 10)));
            p10.add(isLock);
            p10.add(Box.createRigidArea(new Dimension(15, 10)));
            p10.add(noLock);

            message[0] = p1;
            message[1] = p2;
            message[2] = p3;
            message[3] = p4;
            message[4] = p5;
            message[5] = p6;
            message[6] = p7;
            message[7] = p8;
            message[8] = p9;
            message[9] = p10;
            String[] options = {"确定"};
            int result = JOptionPane.showOptionDialog(
                    UserTable.this,                        // the parent that the dialog blocks
                    message,                                    // the dialog message array
                    "添加角色", // the title of the dialog window
                    JOptionPane.DEFAULT_OPTION,                 // option type
                    JOptionPane.PLAIN_MESSAGE,            // message type
                    null,                                       // optional icon, use null to use the default icon
                    options,                                    // options string array, will be made into buttons
                    options[0]                                  // option that should be made into a default button
            );
            if (result == 0) {
                if (name.getText() == null || name.getText().trim().length() == 0) {
                    UIUtils.showWarning("请填写姓名！");
                    return;
                }
                if (sex_boy.isSelected() == false && sex_girl.isSelected() == false) {
                    UIUtils.showWarning("请填写性别！");
                    return;
                }
                editUser.setRealName(name.getText());
                editUser.setUsername(name.getText());
                editUser.setPassword("123456");
                if (sex_boy.isSelected()) {
                    editUser.setSex(1);
                } else {
                    editUser.setSex(0);
                }
                if (birthday.getText() != null && !"".equals(birthday.getText())) {
                    try {
                        java.util.Date birthDate = sdf.parse(birthday.getText());
                        editUser.setBirthday(birthDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                editUser.setMobile(mobile.getText());
                editUser.setHeight(!"".equals(height.getText()) ? Integer.parseInt(height.getText()) : null);
                editUser.setWeight(!"".equals(weight.getText()) ? Integer.parseInt(weight.getText()) : null);
                editUser.setWorkingPlace(workingPlace.getText());
                editUser.setPosition(position.getText());
                editUser.setMedicalHistory(medicalHistory.getText());
                if (noLock.isSelected()) {
                    editUser.setLocked(false);
                } else {
                    editUser.setLocked(true);
                }
                User userDB = userRepository.save(editUser);
                userTableModel.update(userDB, selectedRow);
                UIUtils.showInfo("编辑用户成功！");
            }


        }
    }


    public static void main(String args[]) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new JFrame("JTable Demo");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				UserTable demo = new UserTable();
				frame.add(demo);
				frame.setSize(700, 400);
				frame.setVisible(true);
				demo.start();
			}
		});
	}

}